import React, { useState, createRef, RefObject } from 'react';
import classnames from 'classnames';
import { Input, message } from 'antd';
import { CheckOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

// const styles = require('../index.less');
import styles from '../index.less';

interface IFilterListItemProps {
  selected: boolean
  title: string
  onNameChange: (name: string) => void
  onDelete: (e: React.MouseEvent<HTMLElement>) => void
  selectFilter: () => void
}


const FilterListItem: React.FC<IFilterListItemProps> = (props: any) => {
  const [editing, setEditing] = useState<any>();
  const [inputValue, setInputValue] = useState<any>();
  const { title, onNameChange, selectFilter, onDelete, selected } = props;
  const input: RefObject<Input> = createRef();
  const container: RefObject<HTMLDivElement> = createRef();
  const inputValueChange = (e: any) => {
    setInputValue(e.target.value);
  };
  const enterToFinish = (e: KeyboardEvent) => {
    if (e.keyCode === 13) {
      editFinish();
    }
  };
  const editFallback = (e: any) => {
    if (container && container.current && !container.current.contains(e.target)) {
      setEditing(false);
      setInputValue(title);
      window.removeEventListener('click', editFallback, false);
      window.removeEventListener('keydown', enterToFinish, false);
    }
  };

  const editFinish = (e?: React.MouseEvent<HTMLElement>) => {
    if (e) {
      e.stopPropagation();
    }
    if (inputValue) {
      onNameChange(inputValue);
      setEditing(false);
      window.removeEventListener('click', editFallback, false);
      window.removeEventListener('keydown', enterToFinish, false);
    } else {
      message.error('名称不能为空');
      input && input.current && input.current.input.focus();
    }
  };
  const onDeleteClick = (e: React.MouseEvent<HTMLElement>) => {
    e.stopPropagation();
    onDelete(e);
  };
  const editStart = () => {
    setEditing(true);
    input && input.current && input.current.input.select();
    window.addEventListener('click', editFallback, false);
    window.addEventListener('keydown', enterToFinish, false);
  };
  const contentClass = classnames({
    [styles.treeNodeContent]: true,
    [styles.editing]: editing,
    [styles.listSelect]: selected,
  });
  return (
    <div
      className={contentClass}
      ref={container}
      onClick={selectFilter}
    >
      <h4>{title}</h4>
      <Input
        value={inputValue}
        placeholder='请输入名称'
        size='small'
        onChange={inputValueChange}
        ref={input}
      />
      <CheckOutlined className={styles.confirm} onClick={editFinish} />
      <EditOutlined className={styles.action} onClick={editStart}
      />
      <DeleteOutlined className={styles.action} onClick={onDeleteClick} />
    </div>
  );
};

export default FilterListItem;
